import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';

import { AuthGrantTypeEnum, SmsTypeEnum } from '@/enums/auth';
import { submit } from '@/services/data';

import Footer from '@/components/Footer';
import { LoginParams } from '@/data/login';
import { useTenants } from '@/hooks/auth/useTenants';
import { postAuth } from '@/services/request';
import { LoginForm, ProFormCaptcha, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { Helmet, useModel } from '@umijs/max';
import { Alert, message, Tabs } from 'antd';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import useStyles from './style';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const { styles } = useStyles();

  const [status, setStatus] = useState('');

  const [loginType, setLoginType] = useState<string>(AuthGrantTypeEnum.AdminPassword);
  const { initialState, setInitialState } = useModel('@@initialState');
  const { allTenantValueEnum } = useTenants();

  const fetchUserInfo = async () => {
    const currentUser = await initialState?.fetchUserInfo?.();
    if (currentUser) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser,
        }));
      });
    }
  };

  const handleSubmit = async (values: LoginParams) => {
    const { tenantId } = values;
    const grant_type = loginType;
    let authResult;
    if (grant_type === AuthGrantTypeEnum.AdminPassword) {
      const { username, password } = values;
      authResult = await postAuth({
        grant_type,
        tenantId,
        username,
        password,
      });
    }
    if (grant_type === AuthGrantTypeEnum.AdminPhone) {
      const { phone, captcha } = values;
      authResult = await postAuth({
        grant_type,
        tenantId,
        phone,
        captcha,
      });
    }
    const { access_token, refresh_token, expires_in } = authResult;

    if (access_token) {
      message.success('登录成功！');

      localStorage.setItem('access_token', access_token);
      localStorage.setItem('refresh_token', refresh_token);
      localStorage.setItem('expires_in', expires_in);
      localStorage.setItem('tenantId', tenantId);

      await fetchUserInfo();
      const urlParams = new URL(window.location.href).searchParams;
      const redirectUrl = urlParams.get('redirect') || '/turing/';
      setTimeout(() => {
        window.location.href = redirectUrl;
      }, 100);
      return;
    } else {
      setStatus('error');
      message.error('登录失败，请重试！');
      return;
    }
  };

  const getCaptcha = (phone: string) => {
    return submit('/system/index/sendCaptcha', { phone, smsCode: SmsTypeEnum.PHONE_LOGIN });
  };

  return (
    <div className={styles.container}>
      <Helmet>
        <title>登录页 - Turing - Saas</title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/turing/logo.svg" />}
          title="Turing Saas Login"
          subTitle="Turing Saas 是东半球最好用的 Saas 平台"
          onFinish={async (values) => {
            await handleSubmit(values as LoginParams);
          }}
        >
          <Tabs
            activeKey={loginType}
            onChange={setLoginType}
            centered
            items={[
              {
                key: AuthGrantTypeEnum.AdminPassword,
                label: '账户密码登录',
              },
              {
                key: AuthGrantTypeEnum.AdminPhone,
                label: '手机号登录',
              },
            ]}
          />

          {status === 'error' && loginType === AuthGrantTypeEnum.AdminPassword && (
            <LoginMessage content="账户或密码错误" />
          )}
          {loginType === AuthGrantTypeEnum.AdminPassword && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder="用户名"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder="密码"
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
            </>
          )}

          {status === 'error' && loginType === AuthGrantTypeEnum.AdminPhone && (
            <LoginMessage content="验证码错误" />
          )}
          {loginType === AuthGrantTypeEnum.AdminPhone && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined />,
                }}
                name="phone"
                placeholder="手机号"
                rules={[
                  {
                    required: true,
                    message: '请输入手机号！',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '手机号格式错误！',
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder="请输入验证码"
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} 秒后重新获取`;
                  }
                  return '获取验证码';
                }}
                name="captcha"
                phoneName="phone"
                rules={[
                  {
                    required: true,
                    message: '请输入验证码！',
                  },
                  {
                    pattern: /^\d{6}$/, // 正则：必须是6位数字
                    message: '请输入6位数字验证码！',
                  },
                ]}
                onGetCaptcha={async (phone) => {
                  const result = await getCaptcha(phone);
                  if (!result) {
                    return;
                  }
                  message.success('获取验证码成功！');
                }}
              />
            </>
          )}
          <ProFormSelect
            name="tenantId"
            label="租户选择"
            valueEnum={allTenantValueEnum}
            rules={[
              {
                required: true,
                message: '请选择租户！',
              },
            ]}
          />
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <a
              href="/turing/user/password/forgot"
              style={{
                float: 'right',
                paddingBottom: '20px',
              }}
            >
              忘记密码
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
